package leetcode.leetcode_hot100;

import java.util.Stack;

/**
 * @ClassName T0020
 * @Description 有效地括号
 * @Author Fanxc
 * @DATE 2021/6/19 9:23
 * @Version 1.0
 */
public class T0020 {
    //左括号入栈
    //右括号判断栈顶元素是否匹配，若匹配则出栈
    // 栈为空或者不匹配则为无效的括号
    //到最后，若栈中还有元素，则左括号无效
    class Solution {
        public boolean isValid(String s) {
            if (s==null||s.length()<=0){
                return true;
            }
            Stack<Character> stack=new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c=='('||c=='['||c=='{'){
                    stack.push(c);
                }else if(c==')'){
                    if (stack.isEmpty()){
                        return false;
                    }
                    if (stack.peek()!='('){
                        return false;
                    }else {
                        stack.pop();
                    }
                }else if(c==']'){
                    if (stack.isEmpty()){
                        return false;
                    }
                    if (stack.peek()!='['){
                        return false;
                    }else {
                        stack.pop();
                    }
                }else if(c=='}'){
                    if (stack.isEmpty()){
                        return false;
                    }
                    if (stack.peek()!='{'){
                        return false;
                    }else {
                        stack.pop();
                    }
                }else {
                    return false;
                }
            }
            if (!stack.isEmpty()){
                return false;
            }
            return true;
        }
    }
}
